// pages/cart/cart.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    carts: [],
    selectedAllStatus: false,
    minusStatuses: ['disabled', 'normal'],
    address: [],
    jsCode: ''
  
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log(options);
    this.getCarts();
    this.sum();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },

  getCarts: function () {
    var that = this;
    wx.login({
      success: function (res) {
        // console.log(res)
        that.setData({ jsCode: res.code })
        wx.request({
          url: getApp().globalData.domain + 'api/carts/list',
          data: { openid: getApp().globalData.openid, jsCode: that.data.jsCode },
          header: {
            "Content-Type": "applciation/json"
          },
          method: "GET",
          success: function (res) {
            // console.log(res.data);
            that.setData({
              carts: res.data
            })
          },
          fail: function (err) { },
          complete: function () { }
        })
      }
    })
    
  },
  selectBox: function (e) {
    /*绑定点击事件，将checkbox样式改变为选中与非选中*/
    //拿到下标值，以在carts作遍历指示用
    var index = parseInt(e.currentTarget.dataset.index);
    //原始的icon状态
    var selected = this.data.carts[index].selected;
    console.log(selected);
    var carts = this.data.carts;
    // 对勾选状态取反
    carts[index].selected = !selected;
    // 写回经点击修改后的数组
    this.setData({
      carts: carts
    });
    this.sum();
  },
  bindSelectAll: function () {
    // 环境中目前已选状态
    var selectedAllStatus = this.data.selectedAllStatus;
    // 取反操作
    selectedAllStatus = !selectedAllStatus;
    // 购物车数据，关键是处理selected值
    var carts = this.data.carts;
    // 遍历
    for (var i = 0; i < carts.length; i++) {
      carts[i].selected = selectedAllStatus;
    }
    this.setData({
      selectedAllStatus: selectedAllStatus,
      carts: carts
    });
    // this.data.cid.push(this.data.carts[index].id);
    this.sum();
  },

  bindMinus: function (e) {
    var index = parseInt(e.currentTarget.dataset.index);
    var num = this.data.carts[index].num;
    // 如果只有1件了，就不允许再减了
    if (num > 1) {
      num--;
    }
    var minusStatus = num <= 1 ? 'disabled' : 'normal';
    var carts = this.data.carts;
    carts[index].num = num;
    var minusStatuses = this.data.minusStatuses;
    minusStatuses[index] = minusStatus;

    this.setData({
      carts: carts,
      minusStatuses: minusStatuses
    });
    this.sum();
  },
  bindPlus: function (e) {
    var index = parseInt(e.currentTarget.dataset.index);
    var num = this.data.carts[index].num;
    // 自增
    num++;
    // 只有大于一件的时候，才能normal状态，否则disable状态
    var minusStatus = num <= 1 ? 'disabled' : 'normal';
    // 购物车数据
    // console.log(minusStatus)
    var carts = this.data.carts;
    carts[index].num = num;
    // 按钮可用状态
    // console.log(this.data)
    var minusStatuses = this.data.minusStatuses;
    // console.log(minusStatuses)
    minusStatuses[index] = minusStatus;
    // 将数值与状态写回
    this.setData({
      carts: carts,
      minusStatuses: minusStatuses
    });
    this.sum();
  },

  bindManual: function (e) {
    var index = parseInt(e.currentTarget.dataset.index);
    // console.log(e.detail.value)
    var num = e.detail.value;
    var carts = this.data.carts;
    carts[index].num = num
    this.setData({
      carts: carts
    });
    this.sum();
  },
  sum: function () {
    var carts = this.data.carts;
    // 计算总金额
    var total = 0;
    var numbers = 0;
    for (var i = 0; i < carts.length; i++) {
      if (carts[i].selected) {
        total += carts[i].num * carts[i].price;
        numbers += carts[i].num
      }
    }
    // 写回经点击修改后的数组
    this.setData({
      carts: carts,
      total:total,
      numbers:numbers
    });
  },
  userPay: function () {
    var carts = this.data.carts
    // console.log(carts)
    if (carts.length <= 0) {
      wx.showToast({
        title: '请先勾选商品',
        icon: 'none'
      })
      return
    } else {
      //遍历取出已勾选的cid
      var cartIds = []
      var cartNames = []
      var seriesTitles = []
      for (var i = 0; i < carts.length; i++) {
        if (carts[i].selected == 1) {
          cartIds.push(carts[i].id)
          cartNames.push(carts[i].commodity_name)
          seriesTitles.push(carts[i].commodity_series_title)
        }
      }
      console.log(cartNames)
    }
    //将cartIds由数组转字符串，例如1,2
    cartIds = cartIds.join(',')
    cartNames = cartNames.join(',')
    //存于全局变量中

    getApp().globalData.cartIds = cartIds
    getApp().globalData.cartNames = cartNames
    getApp().globalData.seriesTitles = seriesTitles
    getApp().globalData.amount = this.data.total
    wx.navigateTo({
      url: '../cartorder/cartorder?cartIds=' + getApp().globalData.cartIds + '&cartNames=' + getApp().globalData.cartNames + '&seriesTitles=' + getApp().globalData.seriesTitles + '&amount=' + getApp().globalData.amount,
    })
  },
  del:function(e){
    var that = this;
    // console.log(e)
    var index = e.currentTarget.dataset.index
    // console.log(index)
    var id = this.data.carts[index].id
    // console.log(id)
    wx.request({
      url: getApp().globalData.domain + 'api/carts/delete?id='+id,
      data: {
        // id: id,
        // openid: getApp().globalData.openid,
        // token: getApp().globalData.userInfo.token
      },
      header: {
        "Content-Type": "applciation/json"
      },
      method: "POST",
      success: function (res) {
        that.getCarts();
      },
      fail: function (err) { },
      complete: function () { }
    });
  }
})